package com.lxq.sign.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxq.sign.controller.Code;
import com.lxq.sign.controller.Result;
import com.lxq.sign.dao.PageInfDao;
import com.lxq.sign.domain.PageInf;
import com.lxq.sign.service.PageInfService;
import com.lxq.sign.service.util.FTPUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;

@SuppressWarnings({"all"})
@Service
public class PageInfImpl implements PageInfService {

    @Autowired
    PageInfDao pageInfDao;
    FTPClient ftpClient = FTPUtil.connectFtpServer("101.201.101.68", 21, "qidian", "qidian", "gbk");

    @Override
    public Result changePageInf(PageInf pageInf) throws IOException {
        FTPUtil ftpUtil = new FTPUtil();
        List<PageInf> pageInfs = pageInfDao.selectList(null);

        if(pageInfs.size() == 0){
            pageInf.setShowStatus(1);
            pageInfDao.insert(pageInf);
        }else{
            for (PageInf inf : pageInfs) {
                if(inf.getShowStatus() == 1 && inf.getShowWhere().equals(pageInf.getShowWhere())) {
                    inf.setShowStatus(0);
                    pageInfDao.updateById(inf);
                }
            }
            pageInf.setShowStatus(1);
            pageInfDao.insert(pageInf);
        }
        File file =new File("D:\\Page");

        File[] listFiles = file.listFiles();
        boolean loop = false;
        for (File listFile : listFiles) {
            if(listFile.getName().equals(pageInf.getPhotoPath())) {
                loop = ftpClient.storeFile(listFile.getName(), new FileInputStream(listFile));
            }
        }

        return new Result(loop ? Code.INSERT_OK : Code.INSERT_ERR,null);
    }

    @Override
    public Result loginPageInf() {
        QueryWrapper<PageInf> wrapper = new QueryWrapper<>();
        wrapper.eq("show_status",1).and(obj ->{
            obj.eq("show_where","loginPage");
        });
        PageInf pageInf = null;
        try {
            pageInf = pageInfDao.selectOne(wrapper);
        } catch (Exception e) {
            return new Result(Code.GET_ERR,null);
        }
        return new Result(pageInf != null ? Code.GET_OK:Code.GET_ERR,pageInf);
    }

    @Override
    public Result signPageInf() {
        QueryWrapper<PageInf> wrapper = new QueryWrapper<>();
        wrapper.eq("show_status",1).and(obj ->{
            obj.eq("show_where","signPage");
        });
        PageInf pageInf = pageInfDao.selectOne(wrapper);
        return new Result(pageInf != null ? Code.GET_OK:Code.GET_ERR,pageInf);
    }
}
